import configUrl from '@/util/url.js'

let config = {
	url:"",
	data:{},
	method:''
}
const request = (config) => {
    return new Promise((resolve,reject) => {
		if(!config.hideLoading){
			uni.showLoading({
				mask: true
			});
		}
		
		let appUrl = '';
		
		if (config.urlType == 'debug') {
			appUrl = configUrl.Setting + config.url;
		} else {
			appUrl = configUrl.BASE_URL + config.url;
		}
		
		
        uni.request({
            method: config.method || 'get',
            url: appUrl,
            data: config.data,
			timeout: 15000,
            header: (() => {
				let base_config = {
					'Content-Type':'application/x-www-form-urlencoded'
				}
				
				if(config.contentType == 'json') {
					base_config['Content-Type'] = 'application/json';
				}
				
                return base_config;
            })(),
			fail: (e) => {
				reject();
			},
			success:(result)=>{
				if(!config.hideLoading){
					uni.hideLoading();
				}
				let {data} = result
				
				if( config.urlType == 'debug'){
					resolve(data);
					
					return ;
				} else{
					if(data) {
						if (data.code === 0){
							resolve(data)
							
							return ;
						}else{				
							uni.showToast({
							    title: data.msg,
							    duration: 2000,
								icon: 'none'
							});
							
							reject(data)
						}
					} else {
						reject();
					}
				}
			}
        })
    })
}


const uploadFile = (config) => {
	return new Promise((resolve, reject) => {
		uni.uploadFile({
			url: configUrl.BASE_URL + config.url, //仅为示例，非真实的接口地址
		    filePath: config.tempFilePath,
		    name: 'file',
		    formData: config.data,
		    success: (uploadFileRes) => {
				resolve(uploadFileRes);
		    },
			fail() {
				reject();
			}
		});
	})
}

module.exports = {
	request,
	uploadFile
}